﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MEsE.NET.ExtMethods;

namespace MEsE.NET.Asetukset
{
    public class Settings: IDisposable
    {
        static Dictionary<string, string> properties = new Dictionary<string, string>();
        static string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "MEsE\\settings.ini");

        static Settings()
        {
            try
            {
                string fileContent = string.Empty;

                using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open)))
                    fileContent = reader.ReadToEnd();

                var rivit = fileContent.Split(Environment.NewLine.ToCharArray()).Where(line => !line.StartsWith("#") && line.Contains("="));
                new List<string>(rivit).ForEach(line =>
                {
                    string key = line.Split('=')[0].Trim(),
                        value = line.Split('=')[1].Trim();

                    bool isBold = key == "Bold";

                    properties.Add(key, value);
                });
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message + "\n\n" + ex.GetType().Name);
                throw ex;
            }
        }


        /// <summary>
        /// Tallentaa kaikki asetukset levylle
        /// </summary>
        public void Save()
        {
            using (StreamWriter writer = new StreamWriter(new FileStream(path, FileMode.Create)))
            {
                properties.Keys.ForEach<string>(key =>
                    writer.WriteLine(key + " = " + properties[key]));
            }
        }

        public string this[string key]
        {
            get
            {
                return properties[key];
            }
            set
            {
                if (properties.Keys.Contains(key))
                    properties[key] = value;
                else
                    properties.Add(key, value);
            }
        }

        public void Dispose()
        {
            Save();
        }
    }
}
